const fs = require('fs');
const path = require('path');

const folderPath = './user'
const folderName = 'danger'
const folderName2 = 'danger'

let svgNameJson = ''
let svgNameList = []
getFile(folderPath)

function getFile (url) {
  svgNameJson = ''
  svgNameList = []
  const files = fs.readdirSync(url);
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    const filePath = path.join(url, file);
    setFile(filePath, file)
  }
}
async function setFile (path, file) {
  fs.readFile(`./${path}`, 'utf8', (err, data) => {
    if (err) {
      console.error(err);
      return;
    }
    const fillList = [...new Set(data.match(/fill="([\s\S]*?)"/g))]
    if (fillList.length === 2) {
      for (let i = 0; i < fillList.length; i++) {
        data = data.replace(new RegExp(fillList[i], 'g'),'')
      }
    }

    const svgName = file
    file = file.replace(new RegExp('_', 'g'),'-')
    file = file.replace(new RegExp('v2', 'g'),'-2')
    file = file.replace(new RegExp('V2', 'g'),'-3')
    if (folderName.length !== 0) {
      file = file.replace(`${folderName}_`,'')
      file = file.replace(`${folderName}-`,'')
    }
    const modifiedStr = file.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
    let result = modifiedStr.startsWith('-') ? modifiedStr.substring(1) : modifiedStr;
    const index = svgNameList.findIndex(v => v === result)
    if (index !== -1) {
      result = result.replace('.svg', '')
      result += '-2.svg'
    }
    svgNameList.push(result)
    svgNameJson += `
    "${svgName.replace('.svg', '')}":"${folderName.length !== 0 ? folderName2 + '-' :''}${result.replace('.svg', '')}",`
    fs.writeFile(`./svgNameJson.json`,`{ ${svgNameJson} }`, 'utf8', (err) => {
      if (err) {
        return;
      }
    });
    fs.writeFile(`./aauser/${result}`, `${data}`, 'utf8', (err) => {
      if (err) {
        return;
      }
    });
  });
}
